package com.sp.scmdb.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sp.scmdb.bean.EmpReportBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.common.action.BaseAction;
import com.sp.scmdb.entity.Department;
import com.sp.scmdb.entity.Duty;
import com.sp.scmdb.entity.Report_Upload;
import com.sp.scmdb.entity.WorkType;
import com.sp.scmdb.exception.ExcelException;
import com.sp.scmdb.service.DepartmentService;
import com.sp.scmdb.service.DutyService;
import com.sp.scmdb.service.EmpReportService;
import com.sp.scmdb.service.ExportExcelService;
import com.sp.scmdb.service.WorkTypeService;
import com.sp.scmdb.utils.GroupList;

@Controller("empReportAction")
@Scope("prototype")
public class EmpReportAction extends BaseAction<EmpReportBean> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(EmpReportAction.class);
	private DepartmentService departmentService;
	private DutyService dutyService;
	private EmpReportService empReportService;
	private WorkTypeService workTypeService;
	private ExportExcelService exportExcelService;
	private InputStream excelStream;
	private String fileName;

	@Autowired
	public void setExportExcelService(ExportExcelService exportExcelService) {
		this.exportExcelService = exportExcelService;
	}

	@Autowired
	public void setEmpReportService(EmpReportService empReportService) {
		this.empReportService = empReportService;
	}

	@Autowired
	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	@Autowired
	public void setDutyService(DutyService dutyService) {
		this.dutyService = dutyService;
	}

	@Autowired
	public void setWorkTypeService(WorkTypeService workTypeService) {
		this.workTypeService = workTypeService;
	}

	@SuppressWarnings("unchecked")
	public String findAll() {
		try {
			UserBean user = (UserBean) session.get("user");
			List<Department> depList = departmentService.queryAll(user);
			List<Duty> dutyList = dutyService.queryAll();
			List<WorkType> workTypeList = workTypeService.queryAll();
			session.put("depList", depList);
			session.put("dutyList", dutyList);
			session.put("workTypeList", workTypeList);
			return SUCCESS;
		} catch (Exception e) {
			log.error("get report failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String initDayReport() {
		try {
			session.remove("empDayReportBean");
			return "dayReport";
		} catch (Exception e) {
			log.error("init employee day report failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	@SuppressWarnings("unchecked")
	public String initMonthReport() {
		try {
			session.remove("maxDay");
			session.remove("monthReportBean");
			DateTime startTime = new DateTime();
			session.put("maxDay", GroupList.groupDayOfMonth(startTime.dayOfMonth().getMaximumValue()));
			return "monthReport";
		} catch (Exception e) {
			log.error("init employee month report failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	@SuppressWarnings("unchecked")
	public String findDayReport() {
		try {
			EmpReportBean empReportBean = null;
			if (StringUtils.isNotEmpty(pageName)) {
				empReportBean = (EmpReportBean) session.get("empDayReportBean");
			} else {
				entity.setPageNo(1);
			}
			if (StringUtils.isNotEmpty(entity.getInTime()) && StringUtils.isNotEmpty(entity.getOutTime())) {
				setEntity(empReportService.getDayReportData(entity, empReportBean));
				session.put("empDayReportBean", entity);
			} else {
				session.remove("empDayReportBean");
				messageSession(CommonParamter.CHECK_FLG, "请输入查询时间段");
			}
			return "dayReport";
		} catch (Exception e) {
			log.error("get employee day report failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	@SuppressWarnings("unchecked")
	public String findMonthReport() {
		try {
			session.remove("maxDay");
			DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM");
			DateTime startTime = new DateTime();
			if (StringUtils.isNotEmpty(entity.getInTime())) {
				startTime = formatter.parseDateTime(entity.getInTime());
				EmpReportBean empMonthReportBean = null;
				if (StringUtils.isNotEmpty(pageName)) {
					empMonthReportBean = (EmpReportBean) session.get("monthReportBean");
				} else {
					entity.setPageNo(1);
				}
				setEntity(empReportService.getMonthReportData(entity, empMonthReportBean));
				session.put("monthReportBean", entity);
			} else {
				session.remove("monthReportBean");
				messageSession(CommonParamter.CHECK_FLG, "请输入查询月份");
			}
			session.put("maxDay", GroupList.groupDayOfMonth(startTime.dayOfMonth().getMaximumValue()));
			return "monthReport";
		} catch (Exception e) {
			log.error("get employee month report failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String dayExcelReport() {
		try {
			Workbook wb = new HSSFWorkbook();
			EmpReportBean empReportBean = (EmpReportBean) session.get("empDayReportBean");
			String tableName = "员工日考勤报表";
			if (empReportBean != null) {
				wb = exportExcelService.createDayReportExcel(empReportBean, tableName);
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				tableName = new String("员工日考勤报表".getBytes(), "ISO-8859-1");
				this.fileName = tableName + ".xls";
				wb.write(out);
				excelStream = new ByteArrayInputStream(out.toByteArray());
				out.flush();
				out.close();
				return "excelReport";
			} else {
				messageSession(CommonParamter.CHECK_FLG, "请先查询导出信息!");
				return "dayReport";
			}
		} catch (ExcelException excel) {
			log.error("create dau report excel failed! reason:" + excel.getMessage());
			return "fail";
		} catch (Exception e) {
			log.error("employee  report day excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	@SuppressWarnings("unchecked")
	public String monthExcelReport() {
		try {
			Workbook wb = new HSSFWorkbook();
			Map<Integer, String> dayOfMonth = (Map<Integer, String>) session.get("maxDay");
			EmpReportBean empMonthReportBean = (EmpReportBean) session.get("monthReportBean");
			String tableName = "员工月考勤报表";
			if (empMonthReportBean != null && dayOfMonth != null) {
				wb = exportExcelService.createMonthReportExcel(empMonthReportBean, dayOfMonth, tableName);
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				tableName = new String("员工月考勤报表".getBytes(), "ISO-8859-1");
				this.fileName = tableName + ".xls";
				wb.write(out);
				excelStream = new ByteArrayInputStream(out.toByteArray());
				out.flush();
				out.close();
				return "excelReport";
			} else {
				messageSession(CommonParamter.CHECK_FLG, "请先查询导出信息!");
				return "monthReport";
			}
		} catch (Exception e) {
			log.error("employee  report month excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	@SuppressWarnings("unchecked")
	public String findUpload() {
		try {
			List<Report_Upload> reportList = empReportService.findUpload();
			String refreshTime = "";
			String lastID = "";
			String lastTime = "";
			String state = "";
			String isUsed = "0";
			if (CollectionUtils.isNotEmpty(reportList)) {
				Report_Upload ru = reportList.get(0);
				lastID = ru.getLastID();
				refreshTime = ru.getRefreshTime();
				lastTime = ru.getLastTime();
				state = ru.getState();
				isUsed = ru.getIsUsed();
				if (ru.getIsUsed() == null) {
					isUsed = "0";
				}
			}
			request.setAttribute("refreshTime", refreshTime);
			request.setAttribute("lastID", lastID);
			request.setAttribute("lastTime", lastTime);
			request.setAttribute("state", state);
			session.put("isUsed", isUsed);
			return "findUpload";
		} catch (Exception e) {
			log.error("get report failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String setUp() {
		try {
			String result = "";
			String refreshTime = (String) request.getParameter("refreshTime");
			if (refreshTime != null && !refreshTime.equals("")) {
				result = empReportService.setUp(refreshTime);
			}
			messageSession(result, "");
			return "commitSucc";
		} catch (Exception e) {
			e.printStackTrace();
			log.error("add path failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String cancel() {
		try {
			String isUsed = (String) request.getParameter("isUsed");
			List<Report_Upload> ruList = empReportService.findUpload();
			if (CollectionUtils.isNotEmpty(ruList)) {
				Report_Upload ru = ruList.get(0);
				ru.setIsUsed(isUsed);
				String result = "";
				result = empReportService.initORcancel(ru);
				messageSession(result, "");
			}
			return "commitSucc";
		} catch (Exception e) {
			e.printStackTrace();
			log.error("cancel empReport upload fail! reason:" + e.getMessage());
			return "fail";
		}
	}
}
